﻿// Sheego.Service.X400
// Copyright(C) 2015 Schwab Versand GmbH
//
// This source file is subject to the Microsoft Public License(Ms-PL).
// http://www.opensource.org/licenses/ms-pl.html
// All other rights reserved.
using Sheego.Service.X400.Job.Shared;
using Sheego.Service.X400.Job.Shared.BO;
using Sheego.Service.X400.Job.Shared.Locator;
using Sheego.Service.X400.Job.Shared.Parser;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sheego.Service.X400.Job.Impl.Parser
{
    class EDIFACTParser : IEDIFACTParser
    {
        #region IEDIFACTParser Members

        public IContentType Parse(string Message)
        {
            if (Message == null) //Empty ist erlaubt
                throw new ArgumentNullException("Message");

            if (!Message.StartsWith("UNA")) //No edifact
                return null;

            if (Message.Length < 9) //To short
                return null;

            //Delimiter
            //UNA:+.? '
            //„:“ ist Component Separator
            //„+“ ist Element Separator
            //„.“ ist Dezimaltrennzeichen
            //„?“ ist Release Indicator
            //„ “ ist ein Leerzeichen
            //„'“ ist Segment Terminator


            char ComponentSeparator = Message[3];
            char ElementSeparator = Message[4];
            char SegmentTerminator = Message[8];




            var ContentType = JobLocator.GetContentType();
            ContentType.MIMEType = Constants.ContentTypeEdifact;
            ContentType.SubType = "UNKNOWN";


            //Segmente
            //UNA:+.? '
            //UNB+UNOB:2+4399901806566:14+4054697000009:14+150707:1152+288430000+++++EANCOM'
            //UNH+288430001+SLSRPT:D:96A:UN:EAN004'
            //BGM+73E::9+288430001'
            //DTM+137:20150707:102'
            //DTM+90:20150702:102'
            //...

            using (IEDIFACTParserStream stream = JobLocator.GetEDIFACTParserStream())
            {
                foreach (var segment in Message.Split(SegmentTerminator))
                {
                    var elements = segment.Split(ElementSeparator);

                    var followingElements = new List<string[]>();

                    for(int i = 1;i< elements.Length;i++)
                    {
                        followingElements.Add(elements[i].Split(ComponentSeparator));
                    }

                    //Head-Element und Tail-Elements
                    stream.Write(elements[0], followingElements);
                }
                ContentType.SubType = stream.MessageType;
            }

            return ContentType;
        }

        #endregion
    }
}
